package com.xjtu.platform.admin.controller;

import com.xjtu.platform.admin.*;
import com.xjtu.platform.admin.dto.*;
import com.xjtu.platform.admin.entity.AllAuthor;
import com.xjtu.platform.admin.entity.AuthorList;
import com.xjtu.platform.common.*;
import com.xjtu.platform.reader.dto.GetBookListParamDto;
import com.xjtu.platform.reader.newEntity.LabelAndClass;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.xjtu.platform.common.Constants.ADDRESS_HEAD;
import static com.xjtu.platform.common.Constants.URL_HEAD;
import static com.xjtu.platform.common.Utils.transAddToUrl;

/**
 * @program: platform
 * @description: 管理员控制层
 * @author: Wushanxu
 * @create: 2023-11-17 01:24
 **/

@RestController
@RequestMapping("/admin")
public class AdminController {
    @Resource
    private BookService bookService;

    @Resource
    private ReaderService readerService;
    @Resource
    private CommonService commonService;

    //    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    @Transactional
    @PostMapping("/add/book")
    public Result addBook(@RequestPart("fileList") List<MultipartFile> fileList, @RequestPart("json") AddBookDto dto) throws Exception {
//        String admin_id = TokenUtils.getUserInfo(token, commonService).getUserId();
//        boolean isAddBook = bookService.addBook(addBookDto);
//        if (isAddBook) {
//            return Result.success("添加图书成功");
//        } else {
//            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
//        }
        String bookId = bookService.addBook(dto);
        for (MultipartFile item : fileList) {
            InputStream in = item.getInputStream();
            System.out.println(item.getOriginalFilename());
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
            String time_string = ft.format(timestamp);
            String filename = time_string + '-' + item.getOriginalFilename();
            System.out.println(filename);

            String fileUrl = ADDRESS_HEAD + filename;
            boolean isFile = bookService.addBookFile(bookId, item.getOriginalFilename(), fileUrl);
            if (isFile) {
                System.out.println("添加" + fileUrl + "成功");
            } else {
                System.out.println("添加图片文件" + fileUrl + "失败");
            }
            OutputStream out = new FileOutputStream(fileUrl);
            byte[] b = new byte[10240];
            int len = -1;

            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        }
//        System.out.println(dto.toString());
        if (bookId != null) {
            return Result.success("添加图书成功");
        } else {
            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
        }
    }

    @PostMapping("/add/reader")
    public Result addReader(@RequestBody AddReaderDto addReaderDto, @RequestHeader("Token") String token) {
        String admin_id = TokenUtils.getUserInfo(token, commonService).getUserId();
        boolean isAddReader = readerService.addReader(addReaderDto);
        if (isAddReader) {
            return Result.success("添加读者成功");
        } else {
            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
        }
    }

    @PostMapping("/delete/reader")
    public Result deleteReader(@RequestBody DeleteReaderDto deleteReaderDto, @RequestHeader("Token") String token) {
        String admin_id = TokenUtils.getUserInfo(token, commonService).getUserId();
        boolean isDeleteReader = readerService.deleteReader(deleteReaderDto);
        if (isDeleteReader) {
            return Result.success("删除读者成功");
        } else {
            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
        }
    }

    @PostMapping("/edit/book")
    public Result editBook(@RequestPart("fileList") List<MultipartFile> fileList, @RequestPart("json") EditBookDto editBookDto) throws Exception {
//        String admin_id = TokenUtils.getUserInfo(token, commonService).getUserId();
        boolean isEditBook = bookService.editBook(editBookDto);
        for (MultipartFile item : fileList) {
            InputStream in = item.getInputStream();
            System.out.println(item.getOriginalFilename());
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
            String time_string = ft.format(timestamp);
            String filename = time_string + '-' + item.getOriginalFilename();
            System.out.println(filename);

//            String fileUrl = "E:\\" + filename;
            String fileUrl = ADDRESS_HEAD + filename;
            boolean isFile = bookService.modifyBookFile(editBookDto.getBookId(), item.getOriginalFilename(), fileUrl);
            if (isFile) {
                System.out.println("修改" + fileUrl + "成功");
            } else {
                System.out.println("修改图片文件" + fileUrl + "失败");
            }
            OutputStream out = new FileOutputStream(fileUrl);
            byte[] b = new byte[10240];
            int len = -1;

            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        }
        if (isEditBook) {
            return Result.success("编辑图书成功");
        } else {
            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
        }
    }

    @PostMapping("/edit/reader")
    public Result editReader(@RequestBody EditReaderDto editReaderDto) {
//        String admin_id = TokenUtils.getUserInfo(token, commonService).getUserId();
        boolean isEditReader = readerService.editReader(editReaderDto);
        if (isEditReader) {
            return Result.success("编辑读者成功");
        } else {
            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
        }
    }

    @PostMapping("/delete/book")
    public Result deleteBook(@RequestBody DeleteBookDto deleteBookDto) {
//        String admin_id = TokenUtils.getUserInfo(token, commonService).getUserId();
        boolean isEditReader = bookService.deleteBook(deleteBookDto);
        if (isEditReader) {
            return Result.success("删除书籍成功");
        } else {
            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
        }
    }

    @PostMapping("/reader/list")
    public Result getBookList(@RequestBody GetReaderListParamDto dto) {
        try {
            Map<String, Object> page = readerService.getReaderList(dto);
            System.out.println(page.toString());
            return Result.success("成功", page);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
        }
    }

    @PostMapping("/book/list")
    public Result getBookList(@RequestBody GetBookListDto dto) {
        try {
            Map<String, Object> page = readerService.getBookList(dto);
            System.out.println(page.toString());
            return Result.success("获取图书列表成功", page);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
        }
    }

    @GetMapping("/author/list")
    public Result getAllAuthor() {
        try {
            AllAuthor list = bookService.getAuthorList();
            return Result.success("成功", list);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(Result.ERR_CODE_SYS, Constants.ERROR_MESSAGE);
        }
    }

}
